package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取请求路径
        String requestURI = req.getRequestURI();
        log.info("拦截到请求:{}",requestURI);
        //自定义放行路径
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"

        };
        //判断本次请求路径是否需要放行
        boolean check = check(urls, requestURI);
        //如果不需要处理，则直接放行
        if (check) {
            log.info("本次请求{}不需要处理",requestURI);
            chain.doFilter(req, resp);
            return;
        }
        //判断页面登录状态，如果已登录，则直接放行
        if (req.getSession().getAttribute("employee") != null) {
            //说明已登录了
            //获取用户id
            Long empId = (Long) req.getSession().getAttribute("employee");
            //将id存入ThreadLocal工具类中
            BaseContext.setId(empId);
            //放行
            chain.doFilter(req, resp);
            return;
        }
        //判断手机端登录状态，如果已登录，则直接放行
        if (req.getSession().getAttribute("user") != null) {
            //说明已登录了
            //获取用户id
            Long userId = (Long) req.getSession().getAttribute("user");
            //将id存入ThreadLocal工具类中
            BaseContext.setId(userId);
            //放行
            chain.doFilter(req, resp);
            return;
        }
        //如果未登录则返回未登录结果
        log.info("用户未登录");
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }







    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            //如果一样就放行
            boolean flag = PATH_MATCHER.match(url, requestURI);
            if (flag) {
                return true;
            }
        }
        return false;
    }
}
